package com.yuqing.myblogServe.security;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.yuqing.myblogServe.common.exception.CaptchaException;
import com.yuqing.myblogServe.common.lang.Const;
import com.yuqing.myblogServe.utils.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 图片验证码校验过滤器，在登录过滤器前
 */
@Slf4j
@Component
public class CaptchaFilter extends OncePerRequestFilter {
    private final String loginUrl = "/login";
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    LoginFailureHandler loginFailureHandler;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
       String url = httpServletRequest.getRequestURI();
       if(loginUrl.equals(url) && httpServletRequest.getMethod().equals("POST")) {
           log.info("获取到login链接，正在校验验证码 -- " + url);
           try {
               validate(httpServletRequest);
           }catch (CaptchaException  e) {
               log.info(e.getMessage());
               // 交给登录失败处理器处理
               loginFailureHandler.onAuthenticationFailure(httpServletRequest, httpServletResponse, e);
           }
       }
        filterChain.doFilter(httpServletRequest, httpServletResponse);
    }
    private void validate(HttpServletRequest request) {
        String code = request.getParameter("code");
        String token = request.getParameter("token");
        if (StringUtils.isBlank(code) || StringUtils.isBlank(token)) {
            throw new CaptchaException("验证码不能为空");
        }
        if(!code.equals(redisUtil.hget(Const.CAPTCHA_KEY, token))) {
            throw new CaptchaException("验证码不正确");
        }
        // 一次性使用
        redisUtil.hdel(Const.CAPTCHA_KEY, token);
    }

}
